package com.linlang.grasharepro.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.linlang.grasharepro.model.CollectionDomain;
import com.linlang.grasharepro.utils.DataBaseOpenHelper;

import java.util.ArrayList;

/**
 * 收藏表
 * Created by lenovo on 2016/8/3.
 */
public class CollectionDB {
    public static final String SQLITE_TABLE = "collection";

    public static final String PK = "_id";
    public static final String USER_NAME = "userName";
    public static final String TIME = "time";
    public static final String RELATION_ID = "relationId";

    private static final String TAG = "collectionDbAdapter";
    private DatabaseHelper databaseHelper;
    private SQLiteDatabase sqLiteDatabase;
    private final Context context;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {

            super(context, DataBaseOpenHelper.DATABASE_NAME, null, DataBaseOpenHelper.DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public CollectionDB(Context context) {
        this.context = context;
    }

    public CollectionDB open() throws SQLException {
        databaseHelper = new DatabaseHelper(context);
        sqLiteDatabase = databaseHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }

    /**
     * 新增
     *
     * @param collectionDomain
     * @return
     */
    public int insertCollection(CollectionDomain collectionDomain) {
        long createResult = 0;
        int strid = 0;
        ContentValues initialValues = new ContentValues();
        initialValues.put(USER_NAME, collectionDomain.getUserName());
        initialValues.put(RELATION_ID, collectionDomain.getRelationId());
        initialValues.put(TIME, collectionDomain.getTime());
        try {
            createResult = sqLiteDatabase.insert(SQLITE_TABLE, null, initialValues);

            Cursor cursor = sqLiteDatabase.rawQuery("select last_insert_rowid() from " + SQLITE_TABLE, null);
            if (cursor.moveToFirst())
                strid = cursor.getInt(0);

        } catch (Exception e) {
            // TODO: handle exception
        }
        return strid;
    }

    /**
     * 删除表的全部字段数据
     *
     * @return
     */
    public boolean deleteAllCollection() {
        int doneDelete = 0;
        try {
            doneDelete = sqLiteDatabase.delete(SQLITE_TABLE, null, null);
            Log.w(TAG, Integer.toString(doneDelete));
            Log.e("doneDelete", doneDelete + "");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return doneDelete > 0;
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    public boolean deleteById(String id) {
        int isDelete;
        String[] ids;
        ids = new String[]{id};
        isDelete = sqLiteDatabase.delete(SQLITE_TABLE, PK + "=?", ids);
        Log.e("deleteTicket", "isDelete:" + isDelete + "||" + "ticketID="
                + id);
        return isDelete > 0;
    }

    public boolean deleteByRelationId(String relationId,String userName) {
        int isDelete;
        String[] ids;
        ids = new String[]{relationId,userName};
        isDelete = sqLiteDatabase.delete(SQLITE_TABLE, RELATION_ID + "=? and " + USER_NAME + "=?", ids);
        Log.e("deleteTicket", "isDelete:" + isDelete + "||" + "ticketID="
                + relationId);
        return isDelete > 0;
    }

    /**
     * 获取表中的所有字段
     *
     * @return
     */
    public ArrayList<CollectionDomain> fetchAll() {

        ArrayList<CollectionDomain> collectionDomains = new ArrayList<CollectionDomain>();
        Cursor mCursor = null;
        mCursor = sqLiteDatabase.query(SQLITE_TABLE, new String[]{PK, USER_NAME, RELATION_ID,
                TIME}, null, null, null, null, null);
        if (mCursor.moveToFirst()) {
            do {
                CollectionDomain collectionDomain = new CollectionDomain();
                collectionDomain.set_id(PK);
                collectionDomain.setTime(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(TIME)));
                collectionDomain.setUserName(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(USER_NAME)));
                collectionDomain.setRelationId(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(RELATION_ID)));
                collectionDomains.add(collectionDomain);
            } while (mCursor.moveToNext());
        }
        if (mCursor != null && !mCursor.isClosed()) {
            mCursor.close();
        }
        return collectionDomains;
    }

    /**
     * 获取我的收藏
     *
     * @return
     */
    public ArrayList<CollectionDomain> getMyCollection(String userName) {

        ArrayList<CollectionDomain> collectionDomains = new ArrayList<CollectionDomain>();
        Cursor mCursor = null;
        mCursor = sqLiteDatabase.query(SQLITE_TABLE, new String[]{PK, USER_NAME, RELATION_ID,
                TIME}, USER_NAME + "=?", new String[]{userName}, null, null, null);
        if (mCursor.moveToFirst()) {
            do {
                CollectionDomain collectionDomain = new CollectionDomain();
                collectionDomain.set_id(PK);
                collectionDomain.setTime(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(TIME)));
                collectionDomain.setUserName(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(USER_NAME)));
                collectionDomain.setRelationId(mCursor.getString(mCursor
                        .getColumnIndexOrThrow(RELATION_ID)));
                collectionDomains.add(collectionDomain);
            } while (mCursor.moveToNext());
        }
        if (mCursor != null && !mCursor.isClosed()) {
            mCursor.close();
        }
        return collectionDomains;
    }
}
